//
//  HMDetails.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/10/15.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

class HMDetails: HMViewController {

    var userJsonData = JSON()
    var contentData = Array<Any>()
    /// 是否添加过的亲友
    var isBecomeFriend = false
    private lazy var detailsTable : UITableView = {
        let tableView = UITableView()
        return tableView
    }()
    
    override func setupView() {
        
        self.title = "详细资料"
        view.backgroundColor = UIColor.white
        self.detailsTable.register(PersonalCell.classForCoder(), forCellReuseIdentifier: "PersonalCell")
        self.detailsTable.register(MultiFunctionCell.classForCoder(), forCellReuseIdentifier: "MultiFunctionCell")
        self.detailsTable.delegate = self
        self.detailsTable.dataSource = self
        view.addSubview(self.detailsTable)
        
        self.detailsTable.topAlign(view: view, predicate: "0")
        self.detailsTable.leadingAlign(view: view, predicate: "0")
        self.detailsTable.trailingAlign(view: view, predicate: "0")
        self.detailsTable.bottomAlign(view: view, predicate: "0")
        
        contentData = [["title":"血压","isOn": "false", "sign": "bloodPressure"],
                       ["title": "体重","isOn": "false", "sign": "weight"],
                       ["title": "心率","isOn": "false", "sign": "heartRate"],
                       ["title": "体温","isOn": "false", "sign": "temp"],
                       ["title": "血糖","isOn": "false", "sign": "bloodGlucose"]]
        if isBecomeFriend  {
            agianRequest()
        }
        
    }
    
    
    func agianRequest() {
        NetRequestTool.shareInstance.met = .get
        
        let friendId = userJsonData["id"].stringValue
        NetRequestTool.request(url: "friend/permission", parameters: ["friendId": friendId], success: { (json) in
            
            let permission = json["data"].dictionaryValue
            var i = 0
            for itme in self.contentData {
                var dic1 = itme as! Dictionary<String, Any>
                let str = dic1["sign"] as! String
               
                for it in permission {
                    if it.key == str {
                         dic1["isOn"] = (it.value.boolValue == true ? "true" : "false")
                    }else {
                    }
                }
                
                self.contentData[i] = dic1
                i += 1
                
            }
            
            self.detailsTable.reloadData()
            
        }, fail: { (code, msg) in

        }) { }
        
    }
    
}


extension HMDetails: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        let label = UILabel()
        view.backgroundColor = configure.shareConfigure.HMColor2
        view.addSubview(label)
        
        label.leadingAlign(view: view, predicate: "10")
        label.centerYAlign(view: view)
        if section == 0 {
            label.text = "基本信息"
        }else {
            label.text = "给ta查看的内容"
        }

        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else {
            return contentData.count + 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 100
        }else {
            if indexPath.row == contentData.count {
              return 60
            }
            return 44
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let newCell = cell as! PersonalCell
            newCell.setJson(json: userJsonData)
        }else {
            let newCell = cell as! MultiFunctionCell
            if indexPath.row == contentData.count {
                if isBecomeFriend {
                 newCell.setJson(json: ["title": "保存设置", "type": "button"])
                }else {
                 newCell.setJson(json: ["title": "添加好友", "type": "button"])
                }
            }else {
                let dic = contentData[indexPath.row] as! Dictionary<String, Any>
                let str: String = dic["title"] as! String
                let isOn: String = dic["isOn"] as! String
                newCell.setJson(json: ["title": str, "type": "switch", "isOn": isOn, "id": "\(indexPath.row)"])
            }
           
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
          let  cell = self.detailsTable.dequeueReusableCell(withIdentifier: "PersonalCell") as! PersonalCell
            cell.img.isHidden = true
            return cell
        }else {
           let cell = self.detailsTable.dequeueReusableCell(withIdentifier: "MultiFunctionCell") as! MultiFunctionCell
            cell.delegate = self
            return cell
        }
    }
    
//    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        print("----->>")
//    }

}


extension HMDetails: MultiFunctionDelegate {
    func buttonClick(sender: UIButton) {
        NetRequestTool.shareInstance.met = .post
        var dic: Dictionary<String, Any> = ["userId": self.userJsonData["id"].stringValue]
        var per = Dictionary<String, String>()
//        if isBecomeFriend {
////            dic["permission"] = [String: String]()
//        }
        for itme in contentData {
            var dic1 = itme as! Dictionary<String, Any>
            let str = dic1["title"] as! String
            let isOn = dic1["isOn"] as! String
            
            
            if isBecomeFriend {
                if str == "血压" {
                    per["bloodPressure"] = isOn
                }else if str == "体重" {
                    per["weight"] = isOn
                }else if str == "心率" {
                    per["heartRate"] = isOn
                }else if str == "体温" {
                    per["temp"] = isOn
                }else if str == "血糖" {
                    per["bloodGlucose"] = isOn
                }
            }else {
                if str == "血压" {
                    dic["bloodPressure"] = isOn
                }else if str == "体重" {
                    dic["weight"] = isOn
                }else if str == "心率" {
                    dic["heartRate"] = isOn
                }else if str == "体温" {
                    dic["temp"] = isOn
                }else if str == "血糖" {
                    dic["bloodGlucose"] = isOn
                }
            }
        }
        
        if isBecomeFriend {
            dic["permission"] = per
            // 修改亲友权限
            NetRequestTool.requestForJSON(url: "friend/permission", parameters: dic, success: { (json) in
                self.showToast(message: "修改权限成功！")
            }, fail: { (code, msg) in
                RKDropdownAlert.title("温馨提示！", message: "\(msg)")
            }) {}
        }else {
         
            //小熊： 13192294716  //添加亲友
            NetRequestTool.requestForJSON(url: "friend/request", parameters: dic, success: { (json) in
                self.showToast(message: "申请好友成功,请等待回复！")
            }, fail: { (code, msg) in
                 RKDropdownAlert.title("温馨提示！", message: "\(msg)")
            }) {}
        }
        
        
        
    }
//
    func switchChange(sender: UISwitch) {
        var dic = contentData[sender.tag] as! Dictionary<String, Any>
           dic["isOn"] = (sender.isOn ? "true" : "false")
          contentData[sender.tag] = dic
    }
}
